import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import { getCommentData } from '../../../fetch/detail/detai';
import CommentList from '../../../components/CommentList/index.jsx';
import LoadMore from '../../../components/LoadMore';
import './index.less'
class Comment extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state={
        	data: [],//存储请求的列表数据
            hasMore: false,//当前状态下是否还有更多
            isLoadingMore: false,//当前状态下是“加载中..”还是点击加载更多
            page: 1
        }
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.loadMoreData = this.loadMoreData.bind(this)
    }
    render() {
    	let {id} = this.props;
    	let { loadMoreData } = this
        return (
            <div className="detail-comment-subpage">
                <h2>用户点评</h2>
                {
                    this.state.data.length
                    ? <CommentList data={this.state.data}/>
                    : <div> 加载中...</div>
                }
                {
                	this.state.hasMore ? 
                	<LoadMore
                		{...{
                			isLoadingMore:this.state.isLoadingMore,
                			page:this.state.page,
                			hasMore:this.state.hasMore,
                			loadMoreFn:loadMoreData
                		}}
                	/> : ''
                }

            </div>
        )
    }
    componentDidMount() {
    	this.loadFirstPageData()
    }
    //获取首页数据
    loadFirstPageData(){
    	let id = this.props.id;
    	let page = this.state.page;
    	//请求评论
    	let result = getCommentData(page,id);
    	//console.log(result)
    	//处理数据
    	this.resultHandle(result)
    }
    //处理数据
    resultHandle(result) {
        result.then(res => {
            return res.json()
        }).then(json => {
            const hasMore = json.hasMore
            const data = json.data
            this.setState({
                hasMore: hasMore,
                // 注意，这里讲最新获取的数据，拼接到原数据之后，使用 concat 函数
                data: this.state.data.concat(data)
            })
        }).catch(ex => {
            if (__DEV__) {
                console.error('详情页获取用户评论数据出错, ', ex.message)
            }
        })
    }
    //加载更多
    loadMoreData(){
    	// 记录状态
    	this.setState({
    		isLoadingMore: true
    	});
    	let id = this.props.id;
    	let page = this.state.page;
    	//请求评论
    	let result = getCommentData(page,id);
    	//console.log(result)
    	//处理数据
    	this.resultHandle(result)
    	// 增加 page 技术
        this.setState({
            page: page+1,
            isLoadingMore:false
        });
    }
}

export default Comment